package com.order.controller.common;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.order.config.QiNiuYunConfig;
import com.order.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

@RestController
@RequestMapping("/files")
public class FileController {
    @Autowired
    QiNiuYunConfig qiNiuYunConfig;
    @Value("${server.ip}")
    private String ip;

    @Value("${server.port}")
    private String port;

    private static final String ROOT_PATH = System.getProperty("user.dir") + "/files";

    @PostMapping("/upload")
    public Object upload(MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        // 获取文件扩展名（如"txt"、"png"）
        String extension = FileUtil.extName(originalFilename);

        // 生成完全不含中文的文件名：UUID + 时间戳 + 扩展名
        String fileName = UUID.randomUUID().toString() + "_" +
                System.currentTimeMillis() + "." + extension;

        File finalFile = new File(ROOT_PATH + "/" + fileName);
        if (!finalFile.getParentFile().exists()) {
            finalFile.getParentFile().mkdirs();
        }
        file.transferTo(finalFile);
     //上传到本地
       // String url = "http://" + ip + ":" + port + "/files/download?fileName=" + fileName;
      //  return Result.success(url);
        //上传到七牛云
        InputStream inputStream = new FileInputStream(finalFile);
            String qiniuUrl = qiNiuYunConfig.uploadImgToQiNiu(inputStream, fileName);
        return Result.success(qiniuUrl);
    }


    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        File file = new File(ROOT_PATH + "/" + fileName);  // 文件在存盘存储的对象
        ServletOutputStream os = response.getOutputStream();
        // 处理下载时的文件名显示，保留原始扩展名的可读性
        String displayName = "file_" + System.currentTimeMillis() + "." + FileUtil.extName(fileName);
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("application/octet-stream");
        // os.write(FileUtil.readBytes(file));
        FileUtil.writeToStream(file, os);
        os.flush();
        os.close();
    }
}


